<template>
  <div class="app-container">
    <transition name="el-zoom-in-top">
      <el-form v-show="show" ref="form" :inline="true" :model="form" class="demo-form-inline">
        <el-form-item label="角色名称">
          <el-input v-model="form.name" placeholder="角色名称" clearable />
        </el-form-item>
        <el-form-item label="角色标识">
          <el-input v-model="form.code" placeholder="角色标识" clearable />
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" @click="handleSearch">查询</el-button>
          <el-button icon="el-icon-close" plain @click="handleClearSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </transition>
    <el-row class="g-row">
      <template>
        <el-popconfirm title="确定删除吗？" @confirm="handleDelete(selectedList)">
          <el-button slot="reference" icon="el-icon-delete" type="danger" plain :disabled="selectedList.length === 0">删除</el-button>
        </el-popconfirm>
      </template>
      <el-button icon="el-icon-plus" type="primary" plain @click="handleOpenDialog()">新填</el-button>
      <div style="float: right">
        <el-button icon="el-icon-sort" plain @click="show = !show">查询条件</el-button>
        <el-button icon="el-icon-refresh-left" plain @click="loadList(page.currentPage,page.size)">刷新</el-button>
      </div>
    </el-row>
    <el-row class="g-row">
      <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="14" style="margin-bottom: 10px">
        <el-table
          v-loading="loading"
          :data="tableData"
          stripe
          style="width: 100%"
          :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          highlight-current-row
          @selection-change="selectedChange"
          @current-change="handleChange"
        >
          <el-table-column fixed="left" type="selection" width="55" />
          <el-table-column type="index" width="55" />
          <el-table-column prop="name" label="角色名称" />
          <el-table-column prop="code" label="角色标识" />
          <el-table-column prop="description" label="描述" />
          <el-table-column prop="createTime" label="创建时间" width="170" />
          <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="200">
            <template v-slot="scope">
              <el-button type="text" class="g-button" @click="handleOpenDialog(scope.row)">修改</el-button>
              <el-popconfirm title="确定删除吗？" @confirm="handleDelete(scope.row)">
                <el-button slot="reference" type="text" class="g-button">删除</el-button>
              </el-popconfirm>
              <el-dropdown @command="(command) => handleCommand(command, scope.row)">
                <span style="font-size: 12px" class="el-dropdown-link">更多</span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="handleAssignUser">分配用户</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <el-row class="g-row">
          <el-pagination
            :current-page="page.currentPage"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size="page.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-col>
      <el-col :xs="24" :sm="24" :md="9" :lg="9" :xl="10">
        <el-card class="box-card" shadow="never" style="margin-left: 20px">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配菜单" placement="top">
              <span class="role-span">菜单分配</span>
            </el-tooltip>
            <el-button
              icon="el-icon-check"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="saveMenu"
            >保存</el-button>
          </div>
          <el-tree
            ref="menu"
            :data="menus"
            default-expand-all
            :props="defaultProps"
            accordion
            show-checkbox
            node-key="id"
            :default-checked-keys="menuIds"
            :check-strictly="true"
          />
        </el-card>
      </el-col>

    </el-row>

    <el-dialog
      :title="dialog.title"
      :visible.sync="dialog.visible"
      width="30%"
      :before-close="handleCloseDialog"
    >
      <el-form ref="dialogForm" :rules="rules" :model="dialogForm" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="dialogForm.name" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item label="角色标识" prop="code">
          <el-input v-model="dialogForm.code" placeholder="请输入角色标识" clearable />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="dialogForm.description" type="textarea" placeholder="描述" clearable />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseDialog">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>

  </div>

</template>

<script>
import RoleApi from '@/api/system/role.js'
import MenuApi from '@/api/system/menu.js'

export default {
  name: 'Role',
  data() {
    return {
      loading: true,
      dialog: {
        visible: false,
        title: ''
      },
      show: true,
      page: {
        currentPage: 1,
        size: 10,
        total: 10
      },
      form: {
        name: '',
        code: ''
      },
      dialogForm: {
        name: '',
        code: '',
        email: ''
      },
      tableData: [],
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入角色标识', trigger: 'blur' }
        ]
      },
      selectedList: [],
      // 菜单相关
      menus: [],
      menuIds: [],
      roleId: '',
      defaultProps: { children: 'children', label: 'title', isLeaf: 'leaf' }
    }
  },
  created() {
    this.loadList(this.page.currentPage, this.page.size)
    this.loadMenuOptions()
  },
  methods: {
    loadList(page, size) {
      this.loading = true
      RoleApi.listSysRole(JSON.parse(JSON.stringify(this.form)), page, size).then(res => {
        this.loading = false
        this.page.currentPage = res.data.currentPage
        this.page.size = res.data.size
        this.page.total = res.data.total
        this.tableData = res.data.records
      })
    },
    selectedChange(selectedList) {
      this.selectedList = JSON.parse(JSON.stringify(selectedList))
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.loadList(this.page.currentPage, val)
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.loadList(val, this.page.size)
    },
    handleDelete(data) {
      const ids = []
      if (data.id) {
        ids.push(data.id)
      } else {
        data.map(d => {
          ids.push(d.id)
        })
      }
      RoleApi.delSysRole(ids).then(res => {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.loadList(this.page.currentPage, this.page.size)
      })
    },
    handleSearch() {
      this.loadList(this.page.currentPage, this.page.size)
      this.$message.success('查询成功')
    },
    handleClearSearch() {
      this.form = {
        name: '',
        code: '',
        status: null
      }
    },
    handleOpenDialog(row) {
      this.dialog.visible = true
      if (row) {
        this.dialog.title = '修改'
        this.dialogForm = JSON.parse(JSON.stringify(row))
      } else {
        this.dialog.title = '新添'
      }
    },
    handleCloseDialog() {
      this.dialogForm = {
        username: '',
        name: '',
        gender: '',
        birthday: '',
        tel: '',
        address: '',
        email: ''
      }
      this.$refs.dialogForm.resetFields()
      this.dialog.visible = false
    },
    handleSubmit() {
      this.$refs.dialogForm.validate((valid) => {
        if (valid) {
          if (this.dialogForm.id) {
            RoleApi.updateSysRole(this.dialogForm).then(res => {
              this.$message.success('更新成功')
              this.handleCloseDialog()
              this.loadList(this.page.currentPage, this.page.size)
            })
          } else {
            RoleApi.saveSysRole(this.dialogForm).then(res => {
              this.$message.success('添加成功')
              this.handleCloseDialog()
              this.loadList(this.page.currentPage, this.page.size)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'handleAssignUser':
          this.handleAssignUser(row)
          break
        default:
          break
      }
    },
    handleAssignUser(row) {
      const roleId = row.id
      this.$router.push('/system/role/assignUsers/' + roleId)
    },
    loadMenuOptions() {
      const data = {
        title: '',
        hidden: null
      }
      MenuApi.listSysMenu(data).then(res => {
        this.menus = res.data
      })
    },
    saveMenu() {
      RoleApi.saveSysMenu(this.roleId, this.$refs.menu.getCheckedKeys()).then(res => {
        this.$message.success('保存成功')
        location.reload()
      })
    },
    handleChange(val) {
      this.roleId = val.id
      this.$refs.menu.setCheckedKeys([])
      RoleApi.getSysMenu(val.id).then(res => {
        this.menuIds = res.data
      })
    }
  }
}
</script>

<style scoped>
.g-row{
  margin-top: 10px;
}
.g-button{
  margin: 0;
  padding: 0;
  width: 40px
}
.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}
.el-icon-arrow-down {
  font-size: 12px;
}
</style>
